from django.shortcuts import render,get_object_or_404
from .models import Category,Post,Tag
from django.db.models import Q,F
from django.core.paginator import Paginator
from django.http import HttpResponse

# Create your views here.

def index(request):
     #查询所有分类
    post_list = Post.objects.all() #查询所有文章
    paginator = Paginator(post_list,6)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {'page_obj':page_obj}
    return render(request,'blog/index.html',context)

def category_list(request,category_id):
    category = get_object_or_404(Category,id=category_id)
    posts = category.post_set.all()
    paginator = Paginator(posts, 6)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {'category':category,'page_obj':page_obj}
    return render(request,'blog/list.html',context)

def post_detail(request,post_id):
    #文章详情页
    post = get_object_or_404(Post, id=post_id)

    prev_post = Post.objects.filter(id__lt=post_id).last()
    next_post = Post.objects.filter(id__gt=post_id).first()

    context = {'post': post,'prev_post':prev_post,'next_post':next_post}
    return render(request, 'blog/detail.html', context)

def search(request):

    keyword = request.GET.get('keyword')

    if not keyword:
        post_list = Post.objects.all()

    else:
        post_list = Post.objects.filter(Q(title__icontains=keyword) | Q(desc__icontains=keyword) | Q(content__icontains=keyword))
    paginator = Paginator(post_list, 6)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {'page_obj':page_obj}
    return render(request, 'blog/index.html', context)
